package com.bear.hospital.aspect;

import com.alibaba.fastjson.JSON;
import com.bear.hospital.mapper.ApiLogMapper;
import com.bear.hospital.pojo.ApiLog;
import com.bear.hospital.utils.JwtContext;
import com.bear.hospital.utils.RandomUtil;
import com.bear.hospital.utils.TodayUtil;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Nullable;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;

/**
 * @Author： zmwx
 * @Date： 2025/3/5 10:21
 * @Describe：
 */

@Aspect
@Component
public class LogRequestParamResponseAspect {
    @Resource
    ApiLogMapper apiLogMapper;

    @Around("@annotation(LogRequestParamResponse)")
    public Object logRequestResponse(ProceedingJoinPoint joinPoint) throws Throwable {
        // 获取目标类名
        String className = joinPoint.getTarget().getClass().getName();

        // 获取方法名
        String methodName = joinPoint.getSignature().getName();

        // 获取入参
        Object[] args = joinPoint.getArgs();

        // 获取请求路径
        String requestPath = getRequestPath();

        System.out.println("Class: " + className);
        System.out.println("Method: " + methodName);
        System.out.println("Request Path: " + requestPath);
        System.out.println("Args: " + Arrays.toString(args));

        // 执行方法
        Object result = joinPoint.proceed();

        // 记录出参
        System.out.println("Response: " + result);
        ApiLog apiLog = new ApiLog();
        if (!StringUtils.equals(requestPath, "POST /login/loginSystem")){
            apiLog.setUserName(JwtContext.getUserName());
        }
        apiLog.setId(RandomUtil.generateUniqueId());
        apiLog.setClazz(className);
        apiLog.setDr("0");
        apiLog.setRequestPath(requestPath);
        apiLog.setResponse(JSON.toJSONString(result));
        apiLog.setArgs(JSON.toJSONString(args));
        apiLog.setMethod(methodName);
        apiLog.setCreateTime(TodayUtil.getToday());
        apiLogMapper.insert(apiLog);
        // 这里可以添加代码将类名、方法名、请求路径、入参和出参保存到数据库中

        return result;
    }

    @Nullable
    private String getRequestPath() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        return request.getMethod() + " " + request.getRequestURI();
    }
}
